package cn.itcast.web.action;

import cn.itcast.crm.domain.Customer;
import cn.itcast.domain.base.FixedArea;
import cn.itcast.domain.constant.Constants;
import cn.itcast.service.FixedAreaService;
import cn.itcast.utils.ResponseUtils;
import cn.itcast.web.action.common.BaseAction;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;
import java.util.*;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
public class FixAreaAction extends BaseAction<FixedArea> {
    /*
      model FixedArea
      page  Integer
      rows  Integer
     */
    @Autowired
    private FixedAreaService fixedAreaService;

    @Action(value = "fixedArea_save", results = {@Result(name = "success", location = "./pages/base/fixed_area.html", type = "redirect")})
    public String save() {
        fixedAreaService.save(model);
        return SUCCESS;
    }

    /*
     pageQuery
     id String FixedArea
     company String  FixedArea
     */
    @Action(value = "fixedArea_pageQuery")
    public String pageQuery() {
        //构造查询条件
        Specification<FixedArea> specification = new Specification<FixedArea>() {
            //初始化条件集合
            List<Predicate> predicates = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if (StringUtils.isNotBlank(model.getId())) {
                    Predicate id = cb.equal(root.<String>get("id"), model.getId());
                    predicates.add(id);
                }
                if (StringUtils.isNotBlank(model.getCompany())) {
                    Predicate company = cb.like(root.<String>get("company"), "%" + model.getCompany() + "%");
                    predicates.add(company);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        Pageable pageable = new PageRequest(page - 1, rows);
        Page<FixedArea> pageData = fixedAreaService.findPageData(specification, pageable);
        Map<String, Object> results = new HashMap<>();
        results.put("total", pageData.getTotalElements());
        results.put("rows", pageData.getContent());
        String json = JSONArray.toJSONString(results);
        ResponseUtils.responseWriter(json);
        return NONE;
    }

    //fixedArea_findNoAssociationCustomers.action 未关联查询
    @Action(value = "fixedArea_findNoAssociationCustomers")
    public String findNoAssociationCustomers() {
        Collection<? extends Customer> customers =
               WebClient.create(Constants.CRM_HOST+Constants.CRM_URL+"/services/customerService/noassociationcustomer")
                        .accept(MediaType.APPLICATION_JSON)
                        .getCollection(Customer.class);
        String json=JSONArray.toJSONString(customers);
        ResponseUtils.responseWriter(json);
        return NONE;
    }
    //fixedArea_findHasAssociationFixedAreaCustomers.action",{"id":rows[0].id} 参数customer.id
    @Action(value = "fixedArea_findHasAssociationFixedAreaCustomers")
   public String findHasAssociationFixedAreaCustomers(){
        System.out.println(model.getId());
        Collection<? extends Customer> customers = WebClient.create(Constants.CRM_HOST+Constants.CRM_URL+"/services/customerService/associationfixedareacustomer/" + model.getId())
                .accept(MediaType.APPLICATION_JSON)
                .getCollection(Customer.class);
        String json=JSONArray.toJSONString(customers);
        ResponseUtils.responseWriter(json);
        return NONE;
   }
   //关联定区fixedArea_associationCustomersToFixedArea.action
    private String[] customerIds;

    public void setCustomerIds(String[] customerIds) {
        this.customerIds = customerIds;
    }
    @Action(value = "fixedArea_associationCustomersToFixedArea",results = {@Result(name="success",location = "./pages/base/fixed_area.html",type = "redirect")})
    public String associationCustomersToFixedArea(){
        String customerIdStr = StringUtils.join(customerIds, ",");
        WebClient.create(Constants.CRM_HOST+Constants.CRM_URL+"/services/customerService/associationcustomertofixedarea?customerIdStr="+customerIdStr+"&fixedAreaId="+model.getId())
                .put(null);
        return SUCCESS;
    }

    //action="../../fixedArea_associationCourierToFixedArea.action" //关联快递员和派送时间
    private Integer courierId;
    private Integer takeTimeId;

    public void setCourierId(Integer courierId) {
        this.courierId = courierId;
    }

    public void setTakeTimeId(Integer takeTimeId) {
        this.takeTimeId = takeTimeId;
    }

    @Action(value = "fixedArea_associationCourierToFixedArea",results = {@Result(name = "success",location = "./pages/base/fixed_area.html",type = "redirect")})
    public String associationCourierToFixedArea(){
        fixedAreaService.associationCourierToFixedArea(model,courierId,takeTimeId);

        return SUCCESS;
    }
}
